<template>
  <div class="wrapper">
    <!-- header部分 -->
    <header>
      <i class="fa fa-arrow-left" @click="goBack"></i>
      <div class="title">商家列表</div>
      <div class="placeholder"></div>
    </header>

    <!-- 商家列表部分 -->
    <ul class="business">
      <li
        v-for="item in businessArr"
        :key="item.businessId"
        @click="toBusinessInfo(item.businessId)"
      >
        <div class="business-img">
          <img 
            :src="item.businessImg" 
            @error="handleImageError"
          />
          <div class="business-img-quantity" v-show="item.quantity > 0">
            {{ item.quantity }}
          </div>
        </div>
        <div class="business-info">
          <h3>{{ item.businessName }}</h3>
          <p>
            &#165;{{ item.startPrice }}起送 | &#165;{{ item.deliveryPrice }}配送
          </p>
          <p>{{ item.businessExplain }}</p>
        </div>
      </li>
    </ul>

    <!-- 底部菜单部分 -->
    <Footer></Footer>
  </div>
</template>

<script setup>
import Footer from "@/components/Footer.vue";
import { useRouter, useRoute } from "vue-router";
import { ref, onMounted } from "vue";
import { useUserInfoStore } from '@/stores/user';
import { listBusinessService } from "@/api/business";
import { listCartByUserIdAndBusinessIdService } from "@/api/cart";
import { ElMessage } from 'element-plus';
import { handleAvatarUrl } from '@/utils/imageUtils';
import defaultAvatar from "@/assets/img/default.png";

const router = useRouter();
const route = useRoute();
const userStore = useUserInfoStore();

const foodTypeId = route.query.foodTypeId;
const businessArr = ref([]);

// 返回首页
const goBack = () => {
  router.push('/');
};

// 跳转到商家详情
const toBusinessInfo = (businessId) => {
  router.push({
    path: "/businessInfo",
    query: { 
      businessId,
      foodTypeId: foodTypeId,
      from: 'businessList'
    }
  });
};

// 初始化数据
const init = async () => {
  try {
    const res = await listBusinessService({
      foodTypeId: foodTypeId,
    });
    
    if (res.code === 0) {
      businessArr.value = res.data.map(business => ({
        ...business,
        businessImg: handleAvatarUrl(business.businessImg),
        quantity: 0
      }));

      if (userStore.userInfo) {
        await listCart();
      }
    } else {
      ElMessage.error('获取商家列表失败');
    }
  } catch (error) {
    ElMessage.error('加载数据失败');
  }
};

// 获取购物车列表
const listCart = async () => {
  try {
    const cartPromises = businessArr.value.map(business => 
      listCartByUserIdAndBusinessIdService({
        businessId: business.businessId,
        userId: userStore.userInfo.id
      })
    );

    const responses = await Promise.all(cartPromises);
    
    responses.forEach((response, index) => {
      if (response.code === 0 && Array.isArray(response.data)) {
        businessArr.value[index].quantity = response.data.reduce(
          (total, item) => total + item.quantity, 
          0
        );
      }
    });
  } catch (error) {
    ElMessage.error('获取购物车信息失败');
  }
};

// 处理图片加载错误
// const handleImageError = (event) => {
//   event.target.src = defaultAvatar;
// };

onMounted(() => {
  init();
});
</script>

<style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #ff7043;
  color: #fff;
  font-size: 4.8vw;

  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;

  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4vw;
}

/* 添加返回按钮样式 */
header .fa-arrow-left {
  font-size: 4vw;
  color: #fff;
  width: 8vw;
  cursor: pointer;
}

/* 添加标题样式 */
header .title {
  font-size: 4.5vw;
  font-weight: bold;
}

/* 添加占位元素样式 */
header .placeholder {
  width: 8vw;
}

/****************** 商家列表部分 ******************/
.wrapper .business {
  width: 100%;
  margin-top: 12vw;
  margin-bottom: 14vw;
}

.wrapper .business li {
  width: 100%;
  box-sizing: border-box;
  padding: 2.5vw;
  border-bottom: solid 1px #ddd;
  user-select: none;
  cursor: pointer;

  display: flex;
  align-items: center;
}

.wrapper .business li .business-img {
  /*这里设置为相当定位，成为business-img-quantity元素的父元素*/
  position: relative;
}

.wrapper .business li .business-img img {
  width: 20vw;
  height: 20vw;
  border-radius: 2vw;
  object-fit: cover;
}

.wrapper .business li .business-img .business-img-quantity {
  min-width: 5vw;
  height: 5vw;
  background-color: #ff7043;
  color: #fff;
  font-size: 3.2vw;
  border-radius: 2.5vw;
  padding: 0 1vw;
  
  display: flex;
  justify-content: center;
  align-items: center;
  
  position: absolute;
  right: -1.5vw;
  top: -1.5vw;
  
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.wrapper .business li .business-info {
  margin-left: 3vw;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.wrapper .business li .business-info h3 {
  font-size: 4vw;
  color: #333;
  margin-bottom: 1.5vw;
  font-weight: bold;
}

.wrapper .business li .business-info .price {
  font-size: 4vw;
  color: #ff7043;
  font-weight: bold;
  margin: 1.5vw 0;
}

.wrapper .business li .business-info .price::before {
  content: '¥';
  font-size: 3.5vw;
  margin-right: 0.5vw;
}

.wrapper .business li .business-info p {
  font-size: 3.2vw;
  color: #666;
  margin: 1vw 0;
  line-height: 1.4;
}

.wrapper .business li .business-info .business-explain {
  font-size: 3vw;
  color: #999;
  margin-top: 1vw;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 添加hover效果 */
.wrapper .business li:hover {
  background-color: #f9f9f9;
}

/* 添加点击效果 */
.wrapper .business li:active {
  transform: scale(0.98);
  transition: transform 0.2s;
}
</style>